package com.LeeCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 连续数组
 */

public class Code525 {
    public static void main(String[] args) {
        int[] nums = {0, 1, 1, 1, 1, 1, 0, 0, 0};
        System.out.println(new Code525().findMaxLength(nums));
    }

    public int findMaxLength(int[] nums) {
        int ans = 0, preSum = 0;
        Map<Integer, Integer> cnt = new HashMap<>();
        cnt.put(0, -1);
        for (int i = 0; i < nums.length; i++) {
            // 将0视为-1，1视为1
            preSum += nums[i] == 0 ? -1 : 1;
            if (cnt.containsKey(preSum)) {
                int length = i - cnt.get(preSum);
                ans = Math.max(ans, length);
            } else {
                cnt.put(preSum, i);
            }
        }
        return ans;
    }
}
